package com.substation.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bean.LoginInfo;
import com.greenentity.Area;
import com.greenentity.DataDictionary;
import com.greenentity.Defect;
import com.greenentity.Inspect;
import com.greenentity.Logger;
import com.greenentity.Photo;
import com.greenentity.Ready;
import com.greenentity.SafetyCard;
import com.greenentity.SafetyTool;
import com.greenentity.Substation;
import com.greenentity.Task;
import com.greenentity.Unit;
import com.interfaces.ResponseListener;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;
import com.net.SubstationNet;
import com.substation.R;
import com.substation.greendao.AreaDao;
import com.substation.greendao.DataDictionaryDao;
import com.substation.greendao.DefectDao;
import com.substation.greendao.InspectDao;
import com.substation.greendao.PhotoDao;
import com.substation.greendao.ReadyDao;
import com.substation.greendao.SafetyCardDao;
import com.substation.greendao.SafetyToolDao;
import com.substation.greendao.SubstationDao;
import com.substation.greendao.UnitDao;
import com.substation.ui.adapter.PatroAdapter;
import com.substation.ui.utils.RecyclerViewUtils;
import com.substation.utils.DateUtils;
import com.substation.utils.DialogUtils;
import com.substation.utils.GreenDaoManager;
import com.substation.utils.LocationUtils;
import com.substation.utils.SPUtils;
import com.substation.utils.T;
import com.substation.utils.ZipUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

public class PatrolActivity extends BaseActivity {

    @BindView(R.id.areaList)
    RecyclerView areaList;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.count)
    TextView countText;
    @BindView(R.id.unitList)
    RecyclerView unitList;
    SuperAdapter<DataDictionary> areaSuperAdapter;
    List<DataDictionary> areas = new ArrayList<>();
    SuperAdapter<Unit> unitSuperAdapter;
    List<Unit> units = new ArrayList<>();
    Task task;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    int selected = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_patrol;
    }

    @Override
    protected void initView() {
        areaList.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(context));
        areaList.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        unitList.setLayoutManager(RecyclerViewUtils.getGridLayoutManager(context, 3));
        areaList.setAdapter(areaSuperAdapter = new SuperAdapter<DataDictionary>(R.layout.content_patrol) {
            @Override
            public void bindView(ViewHolder viewHolder, final DataDictionary dataDictionary, final int i) {
                TextView name = viewHolder.getView(R.id.name);
                name.setText(dataDictionary.getValue());
                ImageView select = viewHolder.getView(R.id.selectImage);
                if (dataDictionary.isSelect()) {
                    name.setBackgroundResource(R.drawable.view_bottom_textpre);
                    select.setVisibility(View.VISIBLE);
                } else {
                    name.setBackgroundResource(R.color.transparent);
                    select.setVisibility(View.GONE);
                }
                viewHolder.getView(R.id.layout).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        selected = i;
                        if (dataDictionary.isSelect()) return;
                        for (DataDictionary a : areas) {
                            a.setSelect(false);
                        }
                        dataDictionary.setSelect(true);
                        areaSuperAdapter.notifyDataSetChanged();
                        setUnit(dataDictionary.getCode(), dataDictionary.getValue());
                    }
                });
            }
        });
        areaSuperAdapter.setData(areas);
        unitList.setAdapter(unitSuperAdapter = new PatroAdapter(context));
        unitSuperAdapter.setData(units);
        task = JSON.parseObject((String) SPUtils.get(context, "task", ""), Task.class);
        if (task.getDealTime() == null || task.getDealTime().equals("")) {
            task.setDealTime(DateUtils.getNewTime());
            SPUtils.put(context, "task", JSON.toJSONString(task));
        }
        List<Substation> substations = GreenDaoManager.getInstance().getmDaoSession().getSubstationDao().queryBuilder().where(SubstationDao.Properties.Guid.eq(task.getSubsGuid())).list();
        SPUtils.put(context, "substations", substations.size() > 0 ? substations.get(0).getNames() : "未知变电站");
        areas.clear();
        areas.addAll(GreenDaoManager.getInstance().getmDaoSession().getDataDictionaryDao().queryBuilder().where(DataDictionaryDao.Properties.Type.eq("patrol_route_map")).orderAsc(DataDictionaryDao.Properties.Code).list());
        if (areas.size() > 0) {
            areas.get(selected).setSelect(true);
            setUnit(areas.get(selected).getCode(), areas.get(selected).getValue());
        }
        areaSuperAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initData() {
        task = JSON.parseObject((String) SPUtils.get(context, "task", ""), Task.class);
        if (areas.size() > 0) {
            units.clear();
            setUnit(areas.get(selected).getCode(), areas.get(selected).getValue());
        }
        toolbar.setTitle((String) SPUtils.get(context, "substations", ""));
    }

    private void setUnit(String code, String title) {
        units.clear();
        List<String> guid = new ArrayList<>();
        for (Area a : GreenDaoManager.getInstance().getmDaoSession().getAreaDao().queryBuilder().where(AreaDao.Properties.WorkGuid.eq(task.getWorkGuid())).list()) {
            guid.add(a.getTswcGuid());
        }
        long count = GreenDaoManager.getInstance().getmDaoSession().getUnitDao().queryBuilder().where(UnitDao.Properties.RouteMap.eq(code), UnitDao.Properties.Complete.eq(0), UnitDao.Properties.TswcGuid.in(guid)).count();
        units.addAll(GreenDaoManager.getInstance().getNewSession().getUnitDao().queryBuilder().where(UnitDao.Properties.RouteMap.eq(code), UnitDao.Properties.TswcGuid.in(guid)).orderAsc(UnitDao.Properties.ShowSortNo).list());
        int total = units.size();
        name.setText(title);
        countText.setText("(" + count + "/" + total + ")");
        unitSuperAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_defect, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.upload:
                startLoad();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    void startLoad() {
        List<String> guid = new ArrayList<>();
        for (Area a : GreenDaoManager.getInstance().getmDaoSession().getAreaDao().queryBuilder().where(AreaDao.Properties.WorkGuid.eq(task.getWorkGuid())).list()) {
            guid.add(a.getTswcGuid());
        }
        if (GreenDaoManager.getInstance().getmDaoSession().getUnitDao().queryBuilder().where(UnitDao.Properties.Complete.eq(0), UnitDao.Properties.TswcGuid.in(guid)).count() > 0) {
            showMsg("您还有未巡检项，请巡检完成后提交");
            return;
        }
        if (!setConclusion()) {
            return;
        }
        if (!gotoCard()) {
            return;
        }
        if (!location()) {
            return;
        }
        if (!TextUtils.isEmpty(task.getCondTxt()) && !TextUtils.isEmpty(task.getCondTmp())) {
            upLoad();
        } else {
            SubstationNet.getWeather(context, this);
        }
    }

    @Override
    public void success(int i, String obj) {
        switch (i) {
            case 1:
                T.showLong(context, "任务巡检完成");
                SPUtils.remove(context, "task");
                GreenDaoManager.getInstance().getmDaoSession().getTaskDao().update(task);
                /**添加日志*/
                Logger logger = new Logger();
                logger.setLogsId(System.currentTimeMillis());
                logger.setStatus("新增");
                logger.setUserName(LoginInfo.getInfo(context).getAccountProfileDetails().getNickname());
                logger.setUserId(LoginInfo.getInfo(context).getAccountProfileDetails().getObjectId());
                logger.setSubsGuids(task.getSubsGuid());
                logger.setAddTime(new Date());
                logger.setLogsContent("完成了" + task.getTourTypevalue() + "\n" + "    总共检查了< " + inspectsCount + " >项,其中异常有< " + exCount + " >项。"
                        + "\n"+"巡视结论："+task.getConclusion());
                DataDictionary unique = GreenDaoManager.getInstance().getmDaoSession().getDataDictionaryDao().queryBuilder().
                        where(DataDictionaryDao.Properties.Type.eq("logs_nature"), DataDictionaryDao.Properties.Value.eq(task.getTourTypevalue())).unique();
                logger.setLogsNature(unique == null ? "100" : unique.getCode());
                logger.setLogsNaturevalue(task.getTourTypevalue());
                GreenDaoManager.getInstance().getmDaoSession().insert(logger);
                finish();
                break;
            case 3:
                JSONObject now = ((JSONObject) JSON.parseObject(obj).getJSONArray("HeWeather6").get(0)).getJSONObject("now");
                String cond_txt = now.getString("cond_txt");//天气
                String tmp = now.getString("tmp");//温度
                task.setCondTxt(cond_txt);
                task.setCondTmp(tmp);
                /**开始上传*/
                startLoad();
                break;
            case 999://定位
                String[] ll = obj.split(";");
                task.setLatitude(ll[0]);
                task.setLongitude(ll[1]);
                SPUtils.put(context, "task", JSON.toJSONString(task));
                startLoad();
                break;
        }
    }

    boolean gotoCard() {
        if (task.getPassword() == null || task.getPassword().equals("")) {
            DialogUtils.showMsgDialog(context, "是否填写安全监督卡？", "该任务安全监督卡还未添加，无法上传任务，请先填写安全监督卡。", "填写", "关闭", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    startActivity(new Intent(context, SafetyCardActivity.class));
                }
            }, null);
            return false;
        }
        return true;
    }

    boolean setConclusion() {
        if (task.getConclusion() == null || task.getConclusion().equals("")) {
            DialogUtils.showEditTextDialog(context, "请输入巡视结论", new ResponseListener<String>() {
                @Override
                public void response(String data) {
                    if (TextUtils.isEmpty(data)) {
                        showMsg("巡视结论不能为空");
                        return;
                    }
                    task.setConclusion(data);
                    T.showLong(context, "保存成功");
                    SPUtils.put(context, "task", JSON.toJSONString(task));
                    if (gotoCard()) {
                        upLoad();
                    }
                }
            });
            return false;
        }
        return true;
    }

    int inspectsCount = 0;
    int exCount = 0;

    void upLoad() {
        List<Defect> defects = GreenDaoManager.getInstance().getNewSession().getDefectDao().queryBuilder().where(DefectDao.Properties.WorkGuid.eq(task.getWorkGuid())).list();
        List<String> guid = new ArrayList<String>();
        for (Defect d : defects) {
            guid.add(d.getDefectGuid());
        }
        List<Photo> photos = GreenDaoManager.getInstance().getmDaoSession().getPhotoDao().queryBuilder()
                .where(PhotoDao.Properties.DefectGuid.in(guid), PhotoDao.Properties.PhState.eq("新增")).list();
        if (ZipUtils.zip(photos)) {
            List<Area> areas = GreenDaoManager.getInstance().getNewSession().getAreaDao().queryBuilder().where(AreaDao.Properties.WorkGuid.eq(task.getWorkGuid())).list();
            List<Inspect> inspects = new ArrayList<>();
            for (Area a : areas) {
                List<Unit> us = GreenDaoManager.getInstance().getNewSession().getUnitDao().queryBuilder().where(UnitDao.Properties.TswcGuid.eq(a.getTswcGuid())).list();
                for (Unit u : us) {
                    exCount += u.getExcount();
                    inspects.addAll(GreenDaoManager.getInstance().getmDaoSession().getInspectDao().queryBuilder().where(InspectDao.Properties.UnitGuid.eq(u.getUnitGuid())).list());
                }
            }
            List<SafetyCard> safetyCards = GreenDaoManager.getInstance().getmDaoSession().getSafetyCardDao().queryBuilder().where(SafetyCardDao.Properties.WorkGuid.eq(task.getWorkGuid())).list();
            List<Ready> readies = GreenDaoManager.getInstance().getmDaoSession().getReadyDao().queryBuilder().where(ReadyDao.Properties.WorkGuid.eq(task.getWorkGuid())).list();
            List<SafetyTool> safetyTools = GreenDaoManager.getInstance().getmDaoSession().getSafetyToolDao().queryBuilder().where(SafetyToolDao.Properties.WorkGuid.eq(task.getWorkGuid())).list();
            task.setCompleteTime(DateUtils.getNewTime());
            task.setCurrentWfNo("30");
            inspectsCount = inspects.size();
            SubstationNet.upload(context, task, inspects, defects, safetyCards, readies, safetyTools, photos, PatrolActivity.this);
        }
    }

    boolean location() {
        if (TextUtils.isEmpty(task.getLongitude()) || TextUtils.isEmpty(task.getLatitude())) {
            PermissionGen.needPermission(this, 100, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE
                    , Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE});
            return false;
        } else {
            return true;
        }
    }

    @PermissionSuccess(requestCode = 100)
    public void requestPhotoSuccess() {
        new LocationUtils(context, getApplicationContext(), this);
    }

    @PermissionFail(requestCode = 100)
    public void requestPhotoFail() {
        showMsg("上传数据需要获取位置信息，请设置允许通过");
    }

}
